package cn.phantom.pooltest;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 如何让每周四 18:00:00 定时执行任务
 */
public class TestSchedule {

    public static void main(String[] args) {

        // initDelay 代表当前时间和周四的间隔
        LocalDateTime now = LocalDateTime.now();

        LocalDateTime time = now.withHour(18).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.THURSDAY);

        if (now.compareTo(time) > 0) {
            time = time.plusWeeks(1); // 加一周
        }

        long initDelay = Duration.between(now, time).toMillis();

        // period 代表一周的时间
        long period = 1000 * 60 * 60 * 24 * 7;

        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        pool.scheduleAtFixedRate(() -> {
            System.out.println("running...");
        }, initDelay, period, TimeUnit.MILLISECONDS);

    }
}
